/*
 * Copyright 2005-2013 ttj.net. All rights reserved.
 * Support: http://www.ttj.net
 * License: http://www.ttj.net/license
 */
package com.wwj.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


/**
 * Utils - 图片处理(支持JDK、GraphicsMagick、ImageMagick)
 *
 * @author 体坛加 Team
 * @version 3.0
 */
public final class ImageUtils {

    private static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 处理类型
     */
    private enum Type {

        /**
         * 自动
         */
        auto,

        /**
         * jdk
         */
        jdk,

        /**
         * GraphicsMagick
         */
        graphicsMagick,

        /**
         * ImageMagick
         */
        imageMagick
    }

    /**
     * 处理类型
     */
    private static Type type = Type.auto;

    /**
     * GraphicsMagick程序路径
     */
    private static String graphicsMagickPath;

    /**
     * ImageMagick程序路径
     */
    private static String imageMagickPath;

    /**
     * 背景颜色
     */
    private static final Color BACKGROUND_COLOR = Color.white;

    /**
     * 目标图片品质(取值范围: 0 - 100)
     */
    private static final int DEST_QUALITY = 88;

    static {
        if (graphicsMagickPath == null) {
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.indexOf("windows") >= 0) {
                String pathVariable = System.getenv("Path");
                if (pathVariable != null) {
                    String[] paths = pathVariable.split(";");
                    for (String path : paths) {
                        File gmFile = new File(path.trim() + "/gm.exe");
                        File gmdisplayFile = new File(path.trim() + "/gmdisplay.exe");
                        if (gmFile.exists() && gmdisplayFile.exists()) {
                            graphicsMagickPath = path.trim();
                            break;
                        }
                    }
                }
            }
        }

        if (imageMagickPath == null) {
            String osName = System.getProperty("os.name").toLowerCase();
            if (osName.indexOf("windows") >= 0) {
                String pathVariable = System.getenv("Path");
                if (pathVariable != null) {
                    String[] paths = pathVariable.split(";");
                    for (String path : paths) {
                        File convertFile = new File(path.trim() + "/convert.exe");
                        File compositeFile = new File(path.trim() + "/composite.exe");
                        if (convertFile.exists() && compositeFile.exists()) {
                            imageMagickPath = path.trim();
                            break;
                        }
                    }
                }
            }
        }

        if (type == Type.auto) {
            try {
                IMOperation operation = new IMOperation();
                operation.version();
                IdentifyCmd identifyCmd = new IdentifyCmd(true);
                if (graphicsMagickPath != null) {
                    identifyCmd.setSearchPath(graphicsMagickPath);
                }
                identifyCmd.run(operation);
                type = Type.graphicsMagick;
            } catch (Throwable e1) {
                try {
                    IMOperation operation = new IMOperation();
                    operation.version();
                    IdentifyCmd identifyCmd = new IdentifyCmd(false);
                    identifyCmd.run(operation);
                    if (imageMagickPath != null) {
                        identifyCmd.setSearchPath(imageMagickPath);
                    }
                    type = Type.imageMagick;
                } catch (Throwable e2) {
                    type = Type.jdk;
                }
            }
        }
    }

    /**
     * 不可实例化
     */
    private ImageUtils() {
    }

    /**
     * 等比例图片缩放
     *
     * @param srcFile
     *            源文件
     * @param destFile
     *            目标文件
     * @param destWidth
     *            目标宽度
     * @param destHeight
     *            目标高度
     */
    /*public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
        Assert.notNull(srcFile);
		Assert.notNull(destFile);
		Assert.state(destWidth > 0);
		Assert.state(destHeight > 0);
		if (type == Type.jdk) {
			Graphics2D graphics2D = null;
			ImageOutputStream imageOutputStream = null;
			ImageWriter imageWriter = null;
			try {
				BufferedImage srcBufferedImage = ImageIO.read(srcFile);
				int srcWidth = srcBufferedImage.getWidth();
				int srcHeight = srcBufferedImage.getHeight();
				int width = destWidth;
				int height = destHeight;
				if (srcHeight >= srcWidth) {
					width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
				} else {
					height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
				}
				BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
				graphics2D = destBufferedImage.createGraphics();
				graphics2D.setBackground(BACKGROUND_COLOR);
				graphics2D.clearRect(0, 0, destWidth, destHeight);
				graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

				imageOutputStream = ImageIO.createImageOutputStream(destFile);
				imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())).next();
				imageWriter.setOutput(imageOutputStream);

				String extension = org.springframework.util.StringUtils.getFilenameExtension(destFile.getName());
				if(StringUtils.equals(extension.toLowerCase(), "jpg")){
					ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
					imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
					imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
					imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
				}else{
					imageWriter.write(new IIOImage(destBufferedImage, null, null));
				}
				imageOutputStream.flush();
			} catch (IOException e) {
				logger.error("图片等比例图片缩放异常：" , e);
				e.printStackTrace();
				logger.info("使用原图");
				try {
					FileUtils.copyFile(srcFile, destFile);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			} finally {
				if (graphics2D != null) {
					graphics2D.dispose();
				}
				if (imageWriter != null) {
					imageWriter.dispose();
				}
				if (imageOutputStream != null) {
					try {
						imageOutputStream.close();
					} catch (IOException e) {
						logger.error("图片等比例图片缩放关闭流异常：" , e);
					}
				}
			}
		} else {
			IMOperation operation = new IMOperation();
			operation.thumbnail(destWidth, destHeight);
			operation.gravity("center");
			operation.background(toHexEncoding(BACKGROUND_COLOR));
			operation.extent(destWidth, destHeight);
			operation.quality((double) DEST_QUALITY);
			operation.addImage(srcFile.getPath());
			operation.addImage(destFile.getPath());
			if (type == Type.graphicsMagick) {
				ConvertCmd convertCmd = new ConvertCmd(true);
				if (graphicsMagickPath != null) {
					convertCmd.setSearchPath(graphicsMagickPath);
				}
				try {
					convertCmd.run(operation);
				} catch (IOException e) {
					logger.error("图片等比例图片缩放ConvertCmd io异常（graphicsMagick）：" , e);
					e.printStackTrace();
				} catch (InterruptedException e) {
					logger.error("图片等比例图片缩放ConvertCmd 中断异常（graphicsMagick）：" , e);
					e.printStackTrace();
				} catch (IM4JavaException e) {
					logger.error("图片等比例图片缩放ConvertCmd IM4JavaException异常（graphicsMagick）：" , e);
					e.printStackTrace();
				}
			} else {
				ConvertCmd convertCmd = new ConvertCmd(false);
				if (imageMagickPath != null) {
					convertCmd.setSearchPath(imageMagickPath);
				}
				try {
					convertCmd.run(operation);
				} catch (IOException e) {
					logger.error("图片等比例图片缩放ConvertCmd io异常：" , e);
					e.printStackTrace();
				} catch (InterruptedException e) {
					logger.error("图片等比例图片缩放ConvertCmd 中断异常：" , e);
					e.printStackTrace();
				} catch (IM4JavaException e) {
					logger.error("图片等比例图片缩放ConvertCmd IM4JavaException异常：" , e);
					e.printStackTrace();
				}
			}
		}
	}*/

    /**
     * 等比例图片缩放
     *
     * @param srcFile    源文件
     * @param destFile   目标文件
     * @param destWidth  目标宽度
     * @param destHeight 目标高度
     */
    public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
        Assert.notNull(srcFile);
        Assert.notNull(destFile);
        Assert.state(destWidth > 0);
        Assert.state(destHeight > 0);
        if (type == Type.jdk) {
            Graphics2D graphics2D = null;
            ImageOutputStream imageOutputStream = null;
            ImageWriter imageWriter = null;
            try {
                BufferedImage srcBufferedImage = ImageIO.read(srcFile);
                int srcWidth = srcBufferedImage.getWidth();
                int srcHeight = srcBufferedImage.getHeight();
                int width = destWidth;
                int height = destHeight;
                if (srcHeight >= srcWidth) {
                    width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
                } else {
                    height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
                }
                BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
                graphics2D = destBufferedImage.createGraphics();
                graphics2D.setBackground(BACKGROUND_COLOR);
                graphics2D.clearRect(0, 0, destWidth, destHeight);
                graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

                imageOutputStream = ImageIO.createImageOutputStream(destFile);
                imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())).next();
                imageWriter.setOutput(imageOutputStream);
                String extension = org.springframework.util.StringUtils.getFilenameExtension(destFile.getName());
                if (org.apache.commons.lang3.StringUtils.equals(extension.toLowerCase(), "jpg")) {
                    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
                    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
                    imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
                } else {
                    imageWriter.write(new IIOImage(destBufferedImage, null, null));
                }
                imageOutputStream.flush();
            } catch (IOException e) {
                logger.error("图片等比例图片缩放异常：", e);
                e.printStackTrace();
                logger.info("使用原图");
                try {
                    FileUtils.copyFile(srcFile, destFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } finally {
                if (graphics2D != null) {
                    graphics2D.dispose();
                }
                if (imageWriter != null) {
                    imageWriter.dispose();
                }
                if (imageOutputStream != null) {
                    try {
                        imageOutputStream.close();
                    } catch (IOException e) {
                        logger.error("图片等比例图片缩放关闭流异常：", e);
                    }
                }
            }
        } else {
            IMOperation operation = new IMOperation();
            operation.thumbnail(destWidth, destHeight);
            operation.gravity("center");
            operation.background(toHexEncoding(BACKGROUND_COLOR));
            operation.extent(destWidth, destHeight);
            operation.quality((double) DEST_QUALITY);
            operation.addImage(srcFile.getPath());
            operation.addImage(destFile.getPath());
            if (type == Type.graphicsMagick) {
                ConvertCmd convertCmd = new ConvertCmd(true);
                if (graphicsMagickPath != null) {
                    convertCmd.setSearchPath(graphicsMagickPath);
                }
                try {
                    convertCmd.run(operation);
                } catch (IOException e) {
                    logger.error("图片等比例图片缩放ConvertCmd io异常（graphicsMagick）：", e);
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    logger.error("图片等比例图片缩放ConvertCmd 中断异常（graphicsMagick）：", e);
                    e.printStackTrace();
                } catch (IM4JavaException e) {
                    logger.error("图片等比例图片缩放ConvertCmd IM4JavaException异常（graphicsMagick）：", e);
                    e.printStackTrace();
                }
            } else {
                ConvertCmd convertCmd = new ConvertCmd(false);
                if (imageMagickPath != null) {
                    convertCmd.setSearchPath(imageMagickPath);
                }
                try {
                    convertCmd.run(operation);
                } catch (IOException e) {
                    logger.error("图片等比例图片缩放ConvertCmd io异常：", e);
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    logger.error("图片等比例图片缩放ConvertCmd 中断异常：", e);
                    e.printStackTrace();
                } catch (IM4JavaException e) {
                    logger.error("图片等比例图片缩放ConvertCmd IM4JavaException异常：", e);
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 添加水印
     *
     * @param srcFile
     *            源文件
     * @param destFile
     *            目标文件
     * @param watermarkFile
     *            水印文件
     * @param watermarkPosition
     *            水印位置
     * @param alpha
     *            水印透明度
     *//*
    public static void addWatermark(File srcFile, File destFile, File watermarkFile, WatermarkPosition watermarkPosition, int alpha) {
        Assert.notNull(srcFile);
        Assert.notNull(destFile);
        Assert.state(alpha >= 0);
        Assert.state(alpha <= 100);
        if (watermarkFile == null || !watermarkFile.exists() || watermarkPosition == null || watermarkPosition == WatermarkPosition.no) {
            try {
                FileUtils.copyFile(srcFile, destFile);
            } catch (IOException e) {
                logger.error("添加水印 copy文件异常：" , e);
                e.printStackTrace();
            }
            return;
        }
        if (type == Type.jdk) {
            Graphics2D graphics2D = null;
            ImageOutputStream imageOutputStream = null;
            ImageWriter imageWriter = null;
            try {
                BufferedImage srcBufferedImage = ImageIO.read(srcFile);
                int srcWidth = srcBufferedImage.getWidth();
                int srcHeight = srcBufferedImage.getHeight();
                BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
                graphics2D = destBufferedImage.createGraphics();
                graphics2D.setBackground(BACKGROUND_COLOR);
                graphics2D.clearRect(0, 0, srcWidth, srcHeight);
                graphics2D.drawImage(srcBufferedImage, 0, 0, null);
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

                BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
                int watermarkImageWidth = watermarkBufferedImage.getWidth();
                int watermarkImageHeight = watermarkBufferedImage.getHeight();
                int x = srcWidth - watermarkImageWidth;
                int y = srcHeight - watermarkImageHeight;
                if (watermarkPosition == WatermarkPosition.topLeft) {
                    x = 0;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.topRight) {
                    x = srcWidth - watermarkImageWidth;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.center) {
                    x = (srcWidth - watermarkImageWidth) / 2;
                    y = (srcHeight - watermarkImageHeight) / 2;
                } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                    x = 0;
                    y = srcHeight - watermarkImageHeight;
                } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                    x = srcWidth - watermarkImageWidth;
                    y = srcHeight - watermarkImageHeight;
                }
                graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

                imageOutputStream = ImageIO.createImageOutputStream(destFile);
                imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName())).next();
                imageWriter.setOutput(imageOutputStream);

                String extension = org.springframework.util.StringUtils.getFilenameExtension(destFile.getName());
                if(StringUtils.equals(extension.toLowerCase(), "jpg")){
                    ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
                    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
                    imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
                }else{
                    imageWriter.write(new IIOImage(destBufferedImage, null, null));
                }

                imageOutputStream.flush();
            } catch (IOException e) {
                logger.error("添加水印 （Type.jdk模式）io异常：" , e);
                e.printStackTrace();
            } finally {
                if (graphics2D != null) {
                    graphics2D.dispose();
                }
                if (imageWriter != null) {
                    imageWriter.dispose();
                }
                if (imageOutputStream != null) {
                    try {
                        imageOutputStream.close();
                    } catch (IOException e) {
                        logger.error("添加水印 （Type.jdk模式）关闭流异常：" , e);
                    }
                }
            }
        } else {
            String gravity = "SouthEast";
            if (watermarkPosition == WatermarkPosition.topLeft) {
                gravity = "NorthWest";
            } else if (watermarkPosition == WatermarkPosition.topRight) {
                gravity = "NorthEast";
            } else if (watermarkPosition == WatermarkPosition.center) {
                gravity = "Center";
            } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                gravity = "SouthWest";
            } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                gravity = "SouthEast";
            }
            IMOperation operation = new IMOperation();
            operation.gravity(gravity);
            operation.dissolve(alpha);
            operation.quality((double) DEST_QUALITY);
            operation.addImage(watermarkFile.getPath());
            operation.addImage(srcFile.getPath());
            operation.addImage(destFile.getPath());
            if (type == Type.graphicsMagick) {
                CompositeCmd compositeCmd = new CompositeCmd(true);
                if (graphicsMagickPath != null) {
                    compositeCmd.setSearchPath(graphicsMagickPath);
                }
                try {
                    compositeCmd.run(operation);
                } catch (IOException e) {
                    logger.error("添加水印 （CompositeCmd，graphicsMagick） io异常：" , e);
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    logger.error("添加水印 （CompositeCmd，graphicsMagick） 中断异常：" , e);
                    e.printStackTrace();
                } catch (IM4JavaException e) {
                    logger.error("添加水印 （CompositeCmd，graphicsMagick） IM4JavaException异常：" , e);
                    e.printStackTrace();
                }
            } else {
                CompositeCmd compositeCmd = new CompositeCmd(false);
                if (imageMagickPath != null) {
                    compositeCmd.setSearchPath(imageMagickPath);
                }
                try {
                    compositeCmd.run(operation);
                } catch (IOException e) {
                    logger.error("添加水印 （CompositeCmd） io异常：" , e);
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    logger.error("添加水印 （CompositeCmd） 中断异常：" , e);
                    e.printStackTrace();
                } catch (IM4JavaException e) {
                    logger.error("添加水印 （CompositeCmd） IM4JavaException异常：" , e);
                    e.printStackTrace();
                }
            }
        }
    }*/

    /**
     * 初始化
     */
    public static void initialize() {
    }

    /**
     * 转换颜色为十六进制代码
     *
     * @param color 颜色
     * @return 十六进制代码
     */
    private static String toHexEncoding(Color color) {
        String R, G, B;
        StringBuffer stringBuffer = new StringBuffer();
        R = Integer.toHexString(color.getRed());
        G = Integer.toHexString(color.getGreen());
        B = Integer.toHexString(color.getBlue());
        R = R.length() == 1 ? "0" + R : R;
        G = G.length() == 1 ? "0" + G : G;
        B = B.length() == 1 ? "0" + B : B;
        stringBuffer.append("#");
        stringBuffer.append(R);
        stringBuffer.append(G);
        stringBuffer.append(B);
        return stringBuffer.toString();
    }

    //以下整合自 ttj

    /**
     * 图片水印
     *
     * @param pressImg  水印图片
     * @param targetImg 目标图片
     * @param x         修正值 默认在中间
     * @param y         修正值 默认在中间
     * @param alpha     透明度
     */
    public final static void pressImage(String pressImg, String targetImg, int x, int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            //水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao, null);
            //水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文字水印
     *
     * @param pressText 水印文字
     * @param targetImg 目标图片
     * @param fontName  字体名称
     * @param fontStyle 字体样式
     * @param color     字体颜色
     * @param fontSize  字体大小
     * @param x         修正值
     * @param y         修正值
     * @param alpha     透明度
     */
    public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x, int y, float alpha) {
        try {
            File img = new File(targetImg);
            Image src = ImageIO.read(img);
            int width = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, width, height, null);
            g.setColor(color);
            g.setFont(new Font(fontName, fontStyle, fontSize));
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);
            g.dispose();
            ImageIO.write((BufferedImage) image, "jpg", img);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 缩放
     *
     * @param filePath 图片路径
     * @param height   高度
     * @param width    宽度
     * @param bb       比例不对时是否需要补白
     */
    public static void resize(String filePath, int height, int width, boolean bb) {
        try {
            double ratio = 0.0; //缩放比例
            File f = new File(filePath);
            BufferedImage bi = ImageIO.read(f);
            Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
            //计算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue() / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {
                BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
                g.dispose();
                itemp = image;
            }
            ImageIO.write((BufferedImage) itemp, "jpg", f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        pressImage("G:\\imgtest\\sy.jpg", "G:\\imgtest\\test1.jpg", 0, 0, 0.5f);
        pressText("我是文字水印", "D:/error.jpg", "黑体", 36, Color.white, 80, -10, 0, 0.3f);
        resize("G:\\imgtest\\test1.jpg", 500, 500, true);
    }

    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }

    /**
     * 获取图片宽高
     *
     * @param imgPath
     * @return
     */
    public static float[] getWidthAndHeight(String imgPath) {
        float[] style = new float[2];
        File f = new File(imgPath);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            style[0] = bi.getWidth();
            style[1] = bi.getHeight();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            style[0] = 0;
            style[1] = 0;
            e.printStackTrace();
        } finally {
        }
        return style;
    }

    /**
     * 获取图片宽高
     *
     * @param in
     * @return
     */
    public static float[] getWidthAndHeight(InputStream in) {
        float[] style = new float[2];
        BufferedImage bi;
        try {
            bi = ImageIO.read(in);
            style[0] = bi.getWidth();
            style[1] = bi.getHeight();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            style[0] = 0;
            style[1] = 0;
            e.printStackTrace();
        } finally {
        }
        return style;
    }

    /**
     * 获取图片宽高
     *
     * @param f
     * @return
     */
    public static float[] getWidthAndHeight(File f) {
        float[] style = new float[2];
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            style[0] = bi.getWidth();
            style[1] = bi.getHeight();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            style[0] = 0;
            style[1] = 0;
            e.printStackTrace();
        } finally {
        }
        return style;
    }


    /**
     * 图像切割(按指定起点坐标和宽高切割)
     *
     * @param srcImageFile      源图像地址
     * @param srcImageMaxWidth  源图最大宽度
     * @param srcImageMaxHeight 源图最大高度
     * @param result            切片后的图像地址
     * @param x                 目标切片起点坐标X
     * @param y                 目标切片起点坐标Y
     * @param w                 目标切片宽度
     * @param h                 目标切片高度
     */
    public static void cut(String srcImageFile, int srcImageMaxWidth, int srcImageMaxHeight, String result,
                           int x, int y, int w, int h) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth > srcImageMaxWidth ? srcImageMaxWidth : srcWidth, srcHeight > srcImageMaxHeight ? srcImageMaxHeight : srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, w, h);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, w, h, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag, "JPEG", new File(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图像切割(按指定起点坐标和宽高切割)
     *
     * @param srcImageFileInput 源图像输入流
     * @param srcImageMaxWidth  源图最大宽度
     * @param srcImageMaxHeight 源图最大高度
     * @param result            切片后的图像地址
     * @param x                 目标切片起点坐标X
     * @param y                 目标切片起点坐标Y
     * @param w                 目标切片宽度
     * @param h                 目标切片高度
     */
    public static void cut(InputStream srcImageFileInput, int srcImageMaxWidth, int srcImageMaxHeight, String result,
                           int x, int y, int w, int h) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(srcImageFileInput);
            int srcWidth = bi.getWidth(); // 源图宽度
            int srcHeight = bi.getHeight(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth > srcImageMaxWidth ? srcImageMaxWidth : srcWidth, srcHeight > srcImageMaxHeight ? srcImageMaxHeight : srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, w, h);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, w, h, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                File f = new File(result);
                if (!f.exists())
                    f.mkdirs();
                ImageIO.write(tag, "JPEG", new File(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}